import { API_BASE_URL } from './http';
import { useUserStore } from '../stores/user';
import { storeToRefs } from 'pinia';
/**
 * 通过 EventSource 调用服务端 SSE，流式返回文本。
 * TODO：注意 EventSource 不支持携带 Cookie
 * @param {{ chatId: number|string, userMessage: string, messageType: 'user'|'ai' }} payload
 * @param {{onOpen?:Function,onMessage?:Function,onComplete?:Function,onError?:Function,onPdf?: (url:string)=>void,onCardDrawing,onAddNewConversation}} handlers 回调
 * @returns {Function} close 关闭函数
 */
export function chatWithSSE(payload, handlers = {}) {
  const { onOpen, onMessage, onComplete, onError, onPdf, onCardDrawing,onAddNewConversation } = handlers;
  const { chatId, userMessage, messageType } = payload || {};
  const params = new URLSearchParams();
  // 1. 获取 store 实例
  const userStore = useUserStore()
  // 2. 获取响应式用户数据（推荐使用 storeToRefs 保持响应性）
  const { currentUser } = storeToRefs(userStore)

  if (chatId != null) params.set('chatId', String(chatId));
  if (typeof userMessage === 'string') params.set('userMessage', userMessage);
  if (messageType) params.set('messageType', messageType);
   //获取当前登录用户 ID
  if (currentUser.value != null) params.set('userId', String(currentUser.value.id));
  
  //后端流式响应接口URL（返回SseEmitter）
  const url = `${API_BASE_URL}/ai/manus/chat/sse/history?${params.toString()}`;
  
  //后端流式响应接口URL（返回Flux）
  const flux_url = `${API_BASE_URL}/ai/manus/chat/flux/sse/history?${params.toString()}`;
  
  //通过实现ChatMemory接口实现对话记忆和多轮对话的流式接口URL
  const wu_wa_manus_url = `${API_BASE_URL}/ai/wu_wa_manus/chat?${params.toString()}`;
  

  // 3. 根据后端SSE接口URL创建 SSE 连接对象（EventSource）
  const source = new EventSource(wu_wa_manus_url);
  let receivedAnyChunk = false;

  source.onopen = () => { onOpen && onOpen(); };

  source.onmessage = (event) => {
    const data = event.data ?? '';
    if (data === '[DONE]' || data === '__DONE__') {
      try { source.close(); } catch (_) {}
      onComplete && onComplete();
      return;
    }
    receivedAnyChunk = true;
    // 兜底识别 PDF 链接
    const maybeUrl = String(data).trim();
    const isPdfLike = /(https?:\/\/\S+\.pdf(\?\S*)?$)|(^[A-Za-z]:\\[^\n]*\.pdf$)|(^\/?[^\n]*\.pdf$)/i.test(maybeUrl);
    if (isPdfLike && typeof onPdf === 'function') {
      onPdf(maybeUrl);
      return;
    }
    onMessage && onMessage(data);
  };

  // 自定义事件：发送 PDF 文件 URL
  source.addEventListener('SEND_PDF_FILE', (event) => {
    const data = (event && event.data) || '';
    receivedAnyChunk = true;
    if (onPdf) onPdf(data);
  });

  // 自定义事件：发送抽卡分析数据
  source.addEventListener('SEND_CARD_DRAWING_ANALYSIS', (event) => {
    const data = (event && event.data) || '';
    receivedAnyChunk = true;
    if (onCardDrawing) {
      try {
        const parsedData = JSON.parse(data);
        onCardDrawing(parsedData);
      } catch (error) {
        console.error('解析抽卡分析数据失败:', error);
        // 如果JSON解析失败，尝试解析字符串格式
        onCardDrawing(data);
      }
    }
  });
  
  // 自定义事件：新增对话，需要刷新侧边栏会话列表（后端会返回新增会话的chatId）
  source.addEventListener('SEND_ADD_NEW_CONVERSATION', (event) => {
    const data = (event && event.data) || '';
    receivedAnyChunk = true;
    if (onAddNewConversation) {
      onAddNewConversation(data);
    }
  });

  source.onerror = (err) => {
    if (source.readyState === 2 /* CLOSED */ && receivedAnyChunk) {
      try { source.close(); } catch (_) { /* noop */ }
      onComplete && onComplete();
      return;
    }
    try { source.close(); } catch (_) { /* noop */ }
    onError && onError(err);
  };

  return () => {
    try { source.close(); } catch (_) { /* noop */ }
  };
}

